#!user/bin/python
# -*- coding:UTF-8 -*-

"""
    此模块用于配置、部署和启动bayes服务器。
部署过程包括:
    1、配置mysql连接 config_mysql()
    2、读取邮件集，开始bayes算法训练
    3、训练结果填入数据库
    4、启动bayes_server，部署完成
未开发完全，仍然需要开发优化。
"""

import mysql.connector
from mysql.connector import errorcode
from server.bayes_dao import BayesDao
from server.train_bayes import TrainBayes
from server.bayes_server import BayesServer


def config_mysql():
    """
    mysql配置方法，配置好后测试是否连接上
    :return: (True,配置参数(config)/False,error message)
    """
    host = input('主机(host)：')
    port = input('端口(port)：')
    user = input('用户名(user)：')
    pwd = input('密码(pwd)：')
    database = input('数据库(database)：')

    config = {
        'user': user,
        'password': pwd,
        'host': host,
        'port': port,
        'database': database,
        'charset': 'utf8'
    }

    print('正在测试配置是否正确...')
    print('连接mysql中...')
    try:
        conn = mysql.connector.connect(**config)
        print('mysql连接配置成功！')
        conn.close()
        return True, config
    except mysql.connector.Error as err:
        if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
            print("Something is wrong with your user name or password!")
        elif err.errno == errorcode.ER_BAD_DB_ERROR:
            print("Database does not exist!")
        else:
            print(err)
        return False, str(err)


def config_server():
    host = input("主机ip(host):")
    port = input("监听端口(port):")
    return host, int(port)


def main():
    print('欢迎部署bayes服务器！')
    print('第一步：配置mysql数据库')
    status = config_mysql()
    while not status[0]:
        status = config_mysql()
    mysql_config = status[1]

    print('第二步：训练算法模型')
    while True:
        jump = input("如果你的库中已有训练数据，可跳过该步。是否跳过？(Y/N)")
        if jump == 'N' or jump == 'n':
            train_ground = TrainBayes()
            spam_ham_index = train_ground.get_train_index()
            train_ground.set_train_value(spam_ham_index)
            print('开始训练bayes多项式算法模型...')
            train_ground.train_multinomial()
            print('训练完成！')
            print('开始训练bayes伯努利算法模型...')
            train_ground.train_bernoulli()
            print('训练完成！')
            data = train_ground.get_train_result()
            print('开始将训练结果填入数据库...')
            dao = BayesDao()
            dao.set_config(mysql_config)
            status = dao.insert_train_data(data)
            if not status[0]:
                print('训练结果填入失败:'+status[1])
                return 0
            elif status[0]:
                print('训练结果填入成功！')
            break
        elif jump == 'Y' or jump == 'y':
            break

    print('第三步：配置bayes服务器')
    server_config = config_server()
    print('配置完成！')
    print('开始创建bayes服务器...')
    server = BayesServer(server_config[0], server_config[1], mysql_config)
    print('开始启动...')
    server.start_server()


if __name__ == '__main__':
    main()
